package org.geektimes.projects.user.web.controller;

import org.eclipse.microprofile.config.spi.ConfigSource;
import org.geektimes.configuration.microprofile.config.source.servlet.ServletContextConfigSource;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.projects.user.validation.BeanValidationDemo;
import org.geektimes.web.mvc.controller.PageController;
import org.eclipse.microprofile.config.Config;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;

@Path("/user")
public class LoginController implements PageController {

    // java -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=y -jar user-web/target/user-web-v1-SNAPSHOT-war-exec.jar

    @Resource(name = "bean/UserService")
    private UserService userService;

    @GET
    @POST
    @Path("/register")
    public String register(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return "register-form.jsp";
    }

    @GET
    @POST
    @Path("/saveUser")
    public String saveUser(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phoneNumber = request.getParameter("phoneNumber");
        User user = new User();
        user.setEmail(email);
        user.setName(name);
        user.setPassword(password);
        user.setPhoneNumber(phoneNumber);
        String msg = BeanValidationDemo.validateEntity(user), url = "register-success.jsp";
        if (null != msg) {
            url = "register-form.jsp";
            request.setAttribute("msg", msg);
            return url;
        }
        boolean result = userService.register(user);
        msg = "注册成功";
        if (!result) {
            msg = "注册失败";
            url = "register-form.jsp";
        }
        request.setAttribute("msg", msg);
        return url;
    }

    @GET
    @POST
    @Path("/config")
    public String config (HttpServletRequest request, HttpServletResponse response) throws Throwable {
        ServletContext servletContext = request.getServletContext();
        Config config = (Config) servletContext.getAttribute("WEBAPP_SERVLET_CONFIG");
        Properties properties = new Properties();
        for (ConfigSource configSource : config.getConfigSources()) {
            if (configSource instanceof ServletContextConfigSource) {
                properties.putAll(configSource.getProperties());
                break;
            }
        }
        request.setAttribute("setvlet_config", properties.toString());
        return "index.jsp";
    }

    @GET
    @POST
    @Path("/login")
    public String login (HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return "login-form.jsp";
    }

    @GET
    @POST
    @Path("/userLogin")
    public String userLogin (HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        if (name == null && password == null) {
            String params = null;
            if (request.getParameterNames().hasMoreElements()) {
                params = request.getParameterNames().nextElement();
            }
            System.out.println(params);
            if (null != params) {
                JSONObject jsonObject = (JSONObject) (new JSONParser().parse(params));
                name = (String) jsonObject.get("name");
                password = (String) jsonObject.get("password");
            }
        }
        User user = userService.queryUserByNameAndPassword(name, password);
        PrintWriter writer = response.getWriter();
        String msg = "登录失败", url = "login-form.jsp";
        if (null != user) {
            msg = "登录成功";
            url = "user-info.jsp";
            request.setAttribute("user", user);
            writer.write("alert(" + msg + ")");
        } else {
            writer.write("alert(" + msg + ",用户名或密码错误)");
        }
        return url;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return null;
    }

    public LoginController () {
//        this.userService = ComponentContext.getInstance().getComponent("bean/UserService");
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
